<?php
namespace Admin\Controller;
use Think\AjaxPage;
use Think\Controller;

class GoodController extends CommonController
{
    public function _initialize() {
        $params = array("ajax_goods_list","del_pic");
        parent::_initialize($params);
        $this->assign("now_module" ,"goods");
    }

    //商品列表页面
    public function index()
    {
        //分类列表
        $categories = M('category')->where(array('status' => 1))->order('sort ASC')->select();
        $category = sortCate($categories);
        //品牌列表
        $brand = M('brand')->where(array('status'=>1))->order('id DESC')->select();
        //库存紧张数量
        $stock_warning = M('config')->where( array('conf_key' => 'stock_warning') )->find();
        //店铺列表
        $shop = M('shop')->field('id,shop_name')->order('id DESC')->select();
        // 输入变量
        $this->assign('shops', $shop);
        $this->assign('categories', $category);
        $this->assign('brands', $brand);
        $this->assign('stock_warning', $stock_warning['conf_value']);
        $this->display();
    }

    //商品审核
    public function end_shelves() {
        if (IS_POST) {
            $id = I('post.good_id');
            $end_shelves = M('good')->where( array('id'=>$id) )->getField('end_shelves');
            if ($end_shelves == -1) {
                $bool = M('good')->where( array('id'=>$id) )->save( array('end_shelves'=>1,'reject_msg'=>'', 'appeal_msg'=>'') );
                $this->success('审核成功!', U('Good/index'));
            }
        } else {
            $id = I('get.id');
            $good = M('good')->where( array('id'=>$id) )->find();
            $this->assign('good', $good);
            $this->display();
        }

    }

    //商品下架
    public function off_shelf() {
        if (IS_POST) {
            $good_id = I('post.good_id');
            $data = array(
                'reject_msg' => I('post.reject_msg'),
                'end_shelves' => -1
            );
            M('good')->where( array('id'=>$good_id) )->save($data);
            $this->success('提交成功!', U('Good/index'));
        } else {
            $id = I('get.id');
            $good = M('good')->where( array('id'=>$id) )->find();
            $this->assign('good', $good);
            $this->display();
        }

    }


    // AJAX 读商品列表
    public function ajax_goods_list()
    {
        $where = ' 1 = 1 '; // 搜索条件
        (I('brand_id') !== '') && $where = "$where AND brand_id = ".I('brand_id') ;
        (I('cat_id') !== '') && $where = "$where AND cate = ".I('cat_id') ;
        (I('end_shelves') !== '') && $where = "$where AND end_shelves = ".I('end_shelves') ;
        (I('shop_id') !== '') && $where = "$where AND shop_id = ".I('shop_id') ;


        // 关键词搜索
        $good_name = I('g_name') ? trim(I('g_name')) : '';
        if($good_name) {
            $where = "$where AND (g_name like '%$good_name%' or good_sn like '%$good_name%')" ;
        }
        $intro = I('intro');
        if($intro != '') {
            if($intro == "is_hot"){
                $where = "$where AND hot = 1";
            }else{
                $where = "$where AND recommend = 1";
            }
        }

        $count = D('good')->relation(true)->where($where)->count();
        $Page  = new AjaxPage($count, C('PAGE_NUM'));
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $goodsList = D('good')->relation(true)->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('goods',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }

    //添加商品下架原因
    public function reject_msg() {

    }


    // 添加商品页面和添加商品逻辑
    public function addGood()
    {
        if (IS_POST)
        {
            $brand_id = I('post.brand_id');
            //添加商品的基本信息
            $good = array(
                'g_name' => I('post.g_name'),
                'price' => I('post.price'),
                'info' => trim($_POST['info']),
//                'buy_price'=>I('post.buy_price'),
                'market_price' => I('post.market_price'),
                'sale_num' => I('post.sale_num'),
                'img' => I('post.original_img'),
                'brand_id' => $brand_id,
                'stock' => I('post.stock'),
//                'all_stock'=>I('post.all_stock'),
                'model_id' => I('post.model_id'),
                'shelves' => 1,
                'brief' => I('post.brief'),
                'per_num' => to_int(I('post.per_num')),
                'weight' => to_int(I('post.weight')),
                'thumb' => I('post.thumb')

            );
            // 类目
            $cat_id = I('cat_id');
            (I('cat_id_2') != 0) && ($cat_id = I('cat_id_2'));
            (I('cat_id_3') != 0) && ($cat_id = I('cat_id_3'));
            $good['cate'] = $cat_id;
            $good_sn = trim(I('post.good_sn'));
            $good['good_sn'] = $good_sn;
            if(!$good_sn || $good_sn == ""){
                $good['good_sn'] = "YD" .substr(md5(time()) ,-8);
            }
            $res_arr = M('good')->add($good);

            //商品相册的处理
            $image_pics = I('post.goods_images');
            if (!empty($image_pics)) {
                foreach($image_pics as $v) {
                    if($v != ''){
                        $pics = array('good_id' => $res_arr, 'img' => $v);
                        M('good_pic')->add($pics);
                    }
                }
            }

            // 规格添加
            $spec = I('post.');
            $add_data = array();
            $spec_i = 0;
            foreach($spec as $key => $val)
            {
                // 规格才进入
                if(strstr($key, "spe_") && $val != ''){
                    $spec_key = explode("_" ,$key);
                    if(!empty($spec["spec_" .$spec_key[1]])){
                        $add_data[$spec_i]["spec_id"] = $val;
                        $spec_val = implode("," ,$spec["spec_" .$spec_key[1]]);
                        $add_data[$spec_i]["spec_val"] = $spec_val;
                        $spec_i ++;
                    }
                }
            }
            // 添加
            if(!empty($add_data)){
                foreach($add_data as $val){
                    M('good_spec')->add(array(
                        "good_id" => $res_arr,
                        "spec_id" => $val["spec_id"],
                        "spec_val" => $val["spec_val"]
                    ));
                }
            }
            $agent_brand = M("brand")->where("id = %d" ,array($brand_id))->getField("agent_brand");
            if($agent_brand == 1){
                //返回标示
                $this->success("添加成功,请设置代理价格！" ,U("Good/price", array('id'=>$res_arr)) ,1);
            }else{
                $this->success("添加成功" ,U("Good/index") ,1);
            }
        } else {
            //商品品牌
            $brands = M('brand')->where( array('status'=>1) )->order('id DESC')->select();
            //商品分类
//            $cate = M('category')->where( array('status'=>1) )->order('id DESC')->select();
            $categories = M('category')->where("status = 1 AND pid = 0")->order('sort ASC')->select();
            //代理层级
            $agent_rank = M('agent_rank')->where("rank_status = 1")->order('rank_grade ASC')->select();

            //商品规格
            $spec = M('spec')->order('id DESC')->select();
            $this->assign('spec',$spec);
            $this->assign('agent_rank', $agent_rank);
            //$this->assign('models', $models);
            $this->assign('brands', $brands);
            $this->assign('categories', $categories);
            $this->display();
        }
    }

    //修改商品
    public function edit()
    {
        if (IS_POST) {
            //添加商品的基本信息
            $good = array(
                'g_name' => I('post.g_name'),
                'price' => I('post.price'),
                'info' => trim($_POST['info']),
                'market_price' => I('post.market_price'),
                'sale_num' => I('post.sale_num'),
                'img' => I('post.original_img'),
                'brand_id' => I('post.brand_id'),
                'stock' => I('post.stock'),
                'model_id' => I('post.model_id'),
                'shelves' => 1,
                'brief' => I('post.brief'),
                'per_num' => to_int(I('post.per_num')),
                'weight' => to_int(I('post.weight')),
                'thumb' => I('post.thumb')
            );
            // 类目
            $good_id = to_int(I('post.good_id'));
            $cat_id = I('cat_id');
            (I('cat_id_2') != 0) && ($cat_id = I('cat_id_2'));
            (I('cat_id_3') != 0) && ($cat_id = I('cat_id_3'));
            $good['cate'] = $cat_id;
            $good_sn = trim(I('post.good_sn'));
            $good['good_sn'] = $good_sn;
            if(!$good_sn || $good_sn == ""){
                $good['good_sn'] = "YD" .substr(md5(time()) ,-8);
            }
            $good_msg = M('good')->where("id = %d" ,array($good_id))->find();
            $res_arr = M('good')->where("id = %d" ,array($good_id))->save($good);
            if($res_arr !== false)
            {
//                @unlink($good_msg['img']);
                //商品相册的处理
                $image_pics = I('post.goods_images');
                if (!empty($image_pics)) {
                    foreach($image_pics as $v) {
                        if($v != ''){
                            $pics = array('good_id' => $good_id, 'img' => $v);
                            M('good_pic')->add($pics);
                        }
                    }
                }
                M("good_spec")->where("good_id = %d", array($good_id))->delete();
                // 规格添加
                $spec = I('post.');
                $add_data = array();
                $spec_i = 0;
                foreach($spec as $key => $val)
                {
                    // 规格才进入
                    if(strstr($key, "spe_") && $val != ''){
                        $spec_key = explode("_" ,$key);
                        if(!empty($spec["spec_" .$spec_key[1]])){
                            $add_data[$spec_i]["spec_id"] = $val;
                            $spec_val = implode("," ,$spec["spec_" .$spec_key[1]]);
                            $add_data[$spec_i]["spec_val"] = $spec_val;
                            $spec_i ++;
                        }
                    }
                }
                // 添加
                if(!empty($add_data)){
                    foreach($add_data as $val){
                        M('good_spec')->add(array(
                            "good_id" => $good_id,
                            "spec_id" => $val["spec_id"],
                            "spec_val" => $val["spec_val"]
                        ));
                    }
                }
            }
            //返回标示
            $this->success("操作成功！" ,U("Good/index") ,1);
        } else {
            //商品信息
            $id = I('get.id');
            $good = D('good')->relation(true)->find($id);
            //商品分类
            $categories = M('category')->where(array('status' => 1))->order('sort ASC')->select();
            $category = sortCate($categories);
            //商品品牌
            $brands = M('brand')->order('id DESC')->select();
            //商品模型
            $models = M('model')->order('id DESC')->select();
            //商品相册
            $pics = M('goodPic')->where( array('good_id'=>$id) )->select();
            //属性和属性值的展示
            $all_attr = D('Gmodel')->all_attr($good['model_id']);
            $subsidiary = M('goodSubsidiary')->alias('a')->join('LEFT JOIN __ATTR__ ON a.attr_id=__ATTR__.id')->where( array('good_id'=>$id) )->select();

            //商品的规格和规格值
            $goodSpec = M('goodSpec gs')->field('gs.*,s.s_name')
                ->join('LEFT JOIN  __SPEC__ as s ON gs.spec_id=s.id')
                ->where( array('gs.good_id'=>$id) )->select();

            $spec = M('spec')->order('id ASC')->select();
            $this->assign('spec', $spec);
            $this->assign('goodSpec', $goodSpec);
            $this->assign('subsidiary', $subsidiary);
            $this->assign('all_attr', $all_attr);
            $this->assign('pics', $pics);
            $this->assign('models', $models);
            $this->assign('categories', $category);
            $this->assign('good', $good);
            $this->assign('brands', $brands);
            $this->display();
        }
    }

    //根据商品模型获取商品规格和属性
    public function param_all() {
        $model_id = I('post.model_id');
        $param_all = D('Gmodel')->param_all($model_id);
        $all_attr = D('Gmodel')->all_attr($model_id);
        echo $all_attr;
    }

    //商品图片上传
    public function uploadImg() {
        $pic = D('File')->upload('good');
        echo $pic;
    }

    //商品相册上传并添加
    public function uploadImages() {
        $res = D('File')->upload('goodImages');
        echo $res;
    }

    //操作商品是否推荐，是否热卖，是否上架
    public function changeStatus() {
        $good = M('good')->where( array('id'=>I('post.id')) )->find();
        $field = I('post.field');
        $data[$field] = ($good[$field] == 1) ?  -1: 1;
        $bool = M('good')->where( array('id'=>I('post.id')) )->save($data);
        $this->ajaxReturn($bool);
    }

    //封装拿货价处理代码块
    private function rankPrice() {
        $batch_amt = I('post.batch_amt');//整箱拿货价
        $unit_amt = I('post.unit_amt');//单件拿货价

        foreach ($batch_amt as $key=>$value) {
            foreach ($unit_amt as $k=>$v) {
                if ($key == $k) {
                    $data = array(
                        'good_id' => I('post.id'),
                        'rank_id'=>$k,
                        'unit_amt'=>$v,
                        'batch_amt'=>$value
                    );
                    M('goodRankPrice')->add($data);
                }
                continue;
            }
        }
    }


    //商品的批量上传的显示
    public function batch_upload() {
        if (IS_POST) {

            $data = D('File')->upload2('csv',array('xls'));
            if ($data['state'] == 'error') {
                $this->error($data['info']);
            } else {
                $excel_arr = import_excel('./Uploads/'.$data['dir']);
            }

            foreach ($excel_arr as $k=>$v) {
                $excel_array[$k]['g_name'] = $v[0];
                $excel_array[$k]['brand_id'] = $v[1];
                $excel_array[$k]['cate'] = $v[2];
                $excel_array[$k]['price'] = $v[3];
                $excel_array[$k]['good_sn'] = $v[4];
                $excel_array[$k]['brief'] = $v[5];
                $excel_array[$k]['weight'] = $v[6];
                $excel_array[$k]['stock'] = $v[7];
                $excel_array[$k]['all_stock'] = $v[8];
                $excel_array[$k]['per_num'] = $v[9];
                $excel_array[$k]['info'] = $v[10];
                $excel_array[$k]['recommend'] = $v[11];
                $excel_array[$k]['hot'] = $v[12];
                $excel_array[$k]['is_free'] = $v[13];
                $excel_array[$k]['shelves'] = $v[14];
                $excel_array[$k]['folder'] = $v[15];
            }
            unlink('./Uploads/'.$data['dir']);

            $this->assign('batch_good', $excel_array);
            $this->display('batch_good');
        } else {
            //品牌
            $brand = M('brand')->field('b_name,id')->where( array('status'=>1) )->order('id DESC')->select();
            //分类
            $categories = M('category')->where(array('status' => 1))->order('sort ASC')->select();
            $category = sortCate($categories);
            $this->assign('category', $category);
            $this->assign('brand', $brand);
            $this->display();
        }
    }

    //处理商品批量上传
    public function upload_img() {
        $good = I('post.');
        $len = count($good['g_name']);
        //在插入之前要对商品的分类id和品牌id进行验证,如果错误,提示
        $cate = M('category')->field('id')->where( array('status'=>1) )->select();
        $cate_ids = array_column($cate, 'id');
        $brand = M('brand')->field('id')->where( array('status'=>1) )->select();
        $brand_ids = array_column($brand, 'id');

        $bool = in_array(10,$cate_ids);
        for ($i=0; $i<$len; $i++) {

            $bool = in_array($good['cate'][$i], $cate_ids);
            if (!$bool) {
                $this->error("商品名称为--{$good['g_name'][$i]}--的分类ID填错,请重新填写!");
            }


            $bool = in_array($good['brand_id'][$i], $brand_ids);
            if (!$bool) {
                $this->error("商品名称为--{$good['g_name'][$i]}--的品牌ID填错,请重新填写!");
            }


            $data = array(
                'g_name' => $good['g_name'][$i],
                'brand_id' => $good['brand_id'][$i],
                'cate' => $good['cate'][$i],
                'brief' => $good['brief'][$i],
                'good_sn' => $good['good_sn'][$i],
                'price' => $good['price'][$i],
                'weight' => $good['weight'][$i],
                'stock' => $good['stock'][$i],
                'all_stock' => $good['all_stock'][$i],
                'per_num' => $good['per_num'][$i],
                'info' => $good['info'][$i],
                'recommend' => $good['recommend'][$i],
                'hot' => $good['hot'][$i],
                'is_free' => $good['is_free'][$i],
                'shelves' => $good['shelves'][$i]
            );
            M('good')->add($data);
        }
        $this->success('批量添加成功,请操作批量导入商品图片!', U('Good/index'));
    }

    //批量上传商品相册和图片
    public function good_imgs() {
        if (IS_POST) {

            $date = date('Y-m-d',time());
            $data = D('File')->upload2('zip', array('zip'));
            if ($data['state'] == 'success') {
                $zip_url = './Uploads/'.$data['dir'];
            } else {
                $this->error($data['info']);
            }

            //读取zip压缩包
            $resource = zip_open($zip_url);
            $file = $thumb_arr = array();
            $good_id = array();
            $i = 0;
            while ($dir_resource = zip_read($resource)) {//返回zip档案项目
                $name = zip_entry_name($dir_resource);//读取zip档案项目的名称
                echo $name;
                if( strrchr($name,'/') == '/' ) {
                    array_push($good_id,rtrim($name, '/'));//获取目录的名称(即商品的id)
                };
                if (strpos($name, '.')) {
                    /*                    if (!strpos($name, '_')) {
                                            $fill[0] = './Uploads/temp/'.$name;//保证主图是第一个元素
                                        } else {
                                            $fill[++$i] = './Uploads/temp/'.$name;
                                        }*/

                    $fill[] = './Uploads/temp/'.$name;//保证主图是第一个元素

                }
            }

            //验证压缩包的目录是否正确
            foreach ($good_id as $id) {
                $good = M('good')->where( array('id'=>$id) )->find();
                if (empty($good)) $this->error("压缩包目录设置错误,目录编号为$id");
            }

            $goods_str = implode(',',$good_id);
            //批量上传前,先把商品相册和商品主图进行物理删除和商品图片sql删除
            $where['good_id'] = array('in', $goods_str);
            $good_pic = M('good_pic')->field('img')->where($where)->select();
            foreach ($good_pic as $pic) {//相册物理删除
                unlink($pic['img']);
            }
            $map['id'] = array('in', $goods_str);
            $good_image = M('good')->field('img')->where($map)->select();
            foreach ($good_image as $image) {//主图的物理删除
                unlink($image['img']);
            }
            M('good_pic')->where($where)->delete();//商品相册的sql的删除

            zip_close($resource);
            //解压缩成目录
            get_zip_originalsize($zip_url,'./Uploads/temp/');
            //解压缩后把压缩文件删除
            unlink($zip_url);

            //把目录的文件重命名并复制到相应的目录
            $j=0;
            foreach ($fill as $vi) {
                if(strpos($vi,'_')) {
                    $dir = './Uploads/goods/'.$date;
                } else {
                    $dir = './Uploads/good/'.$date;
                }
                if (!is_dir($dir)) {
                    mkdir($dir);
                }
                $basename = basename($vi);
                $new_dir = $dir.'/'.$basename;
                copy($vi, $new_dir);
                if(!strpos($vi,'_')) {//当时主图的时候,生成缩略图
                    $image = new \Think\Image();
                    $image->open($new_dir);
                    $thumb_dir = $dir.'/small_'.$basename;
                    $image->thumb(180, 180)->save($thumb_dir);
                    $thumb_arr[] = $thumb_dir;
                }


                /*                if (!strpos($new_dir, '_')) {
                                    $file[0] = $new_dir;
                                } else {
                                    $file[++$j] = $new_dir;
                                }*/

                $file[] = $new_dir;


            }

            /*            print_r($file);
                        exit;*/



            //复制到相应的目录后,把temp的解压出来的文件夹删除
            foreach ($good_id as $val) {
                delDirAndFile('./Uploads/temp/'.$val, true);
            }


            //修改商品表和商品相册表
            foreach ($good_id as $value) {
                $k = 0;
                foreach ($file as $v) {
                    if(strpos($v,$value)) {
                        if (!strpos($v, '_')) {
                            $image_data[0] = $v;
                        } else {
                            $image_data[++$k] = $v;
                        }

                    }
                }

                //更新商品的thumb和主图
                $small = insertToStr($image_data[0],26, 'small_');
                M('good')->where( array('id'=>$value) )->save(array('img'=>$image_data[0],'thumb'=>$small));


                unset($image_data[0]);
                foreach ($image_data as $d) {
                    $data['img'] = $d;
                    $data = array(
                        'img' => $d,
                        'good_id' => $value
                    );
                    M('good_pic')->add($data);
                }
                unset($image_data);
            }

            $this->success('导入成功!',U('Good/index'));
        } else {
            $this->display();
        }
    }


    //下载cvs文件
    public function download() {
        $fileName = './Uploads/csv/goods_list.xls';
        download_by_path($fileName);
    }


    // 会员价设置
    public function price() {

        if (IS_POST) {
            M('goodRankPrice')->where( array('good_id' => I('post.id')) )->delete();
            $this->rankPrice();
            $this->success("操作拿货价成功！" ,U("Good/index"));
        } else {
            $id = I('get.id');
            //查询商品的品牌的id
            $good = M('good')->where( array('id'=>$id) )->field("brand_id,g_name")->find();
            $brand_id = $good['brand_id'];
            $brand = M("brand")->where("id = %d AND agent_brand = 1" ,array($brand_id))->find();
            if(!$brand){
                $this->error("代理品牌产品才可设置代理价格！" ,U("Good/index") ,2);
            }
            //代理商拿货价的处理
            $good_rank_price = M('goodRankPrice')->alias('a')
                                                ->join('LEFT JOIN __AGENT_RANK__ as b ON a.rank_id=b.rank_id')
                                                ->where(array('a.good_id'=>$id, 'brand_id'=>$brand_id))
                                                ->order('b.rank_grade ASC')
                                                ->select();

            //如果是已经填写过了拿货价
            if (!empty($good_rank_price)) {
                $this->assign('good_rank_price', $good_rank_price);
            } else {//还没有填写过的时候
                $agent_ranks = M('agentRank')->where( array('rank_status'=>1, 'brand_id'=>$brand_id) )->order('rank_grade ASC')->select();
                $this->assign("agent_rank" ,$agent_ranks);
            }

            $this->assign('id', $id);
            $this->assign('g_name', $good['g_name']);
            $this->display();
        }

    }

    // ajax 编辑页面删除图片
    public function del_pic()
    {
        $pic_id = to_int(I("pic_id"));
        $rs = M("good_pic")->where("id = %d",array($pic_id))->delete();
        $this->ajaxReturn($rs);
    }


}